﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SchoolManagementSystem.Controls;
using CoreData;
using SchoolManagementSystem.Forms.BusinessForm;
namespace SchoolManagementSystem.Details
{
    //Học vien tiem năng
    public partial class TempStudentUC : DetailUC
    {

        bool IsRegister;

        public TempStudentUC()
        {
            InitializeComponent();
            this.ObjectName = "học viên tiềm năng";
            this.Code = "TempStudent";
            this.Type =new  TempStudent();

            cmdDatCoc.Enabled = false;
           

        }


        protected override long DetailDisplay()
        {

            TempStudent data = new TempStudent();
            if (ID > 0)
            {
                data = (TempStudent)RegisterService.RegisterServices.TempStudentService.GetByID(ID);
                cmdDatCoc.Enabled = true;
                data.StatusExt = ((Student_Status)RegisterService.RegisterServices.StudentStatusService.GetByID(data.Status)).Name;
                data.ChannelInfoExt = ((ChannelInfo)RegisterService.RegisterServices.ChannelInfoService.GetByID(data.ChannelInfoID)).Name;
            }
            else
            {
                cmdDatCoc.Enabled = false;
                data.BranchID = "";
                radioGroup_sex.SelectedIndex = 0;
                data.Code = RegisterService.RegisterServices.TempStudentService.GenerateCode();
            }
            txtfirstname.Text = data.FirstName;
            txtlastname.Text = data.LastName;
            buttonEdit_Branch.EditValue = data.BranchID;
            txtcode.Text = data.Code;
            txtnote.Text = data.Note;
            buttonEdit_Status.Tag = data.Status;
            buttonEdit_Status.Text = data.StatusExt;
            ckregister.Checked = data.IsRegister;
            dateEdit_dayofbirth.Text = data.DayOfBirth;
            txtaddress.Text = data.Address;
            cbProvince.EditValue = data.Province;
            txtphonenum.Text = data.Phone;
            txtemail.Text = data.Email;
            radioGroup_sex.EditValue = data.Sex;

            dateEdit_tempcontact.DateTime = data.ContactDate;
            dateEdit_receptioncontact.DateTime = data.ReceptioncontactDate;

            buttonEdit_Channel.Tag = data.ChannelInfoID;
            buttonEdit_Channel.Text = data.ChannelInfoExt;
            memoEdit_noisinh.Text = data.PlaceOfBirth;
            if (data.IsRegister || data.Status==5)
            {
                ckregister.Checked = true;
                cmddangkyhoc.Enabled = false;
              // IsRegister = true;
            }
            else
            {
                ckregister.Checked = false;
                cmddangkyhoc.Enabled = true;
              //  IsRegister = false;
            }
            memoEdit_content.Text = data.Content;
            memoEdit_responsecontent.Text = data.ResponseContent;
            return ID;

        }

        protected override long Save()
        {
            ID = SaveTemp();
            return ID;
        }

        long SaveTemp()
        {
            TempStudent data = new TempStudent();
            if (ID > 0)
            {
                data = (TempStudent)RegisterService.RegisterServices.TempStudentService.GetByID(ID);
            }
            else
            {
                IsRegister = false;
            }
            if (data.ID <= 0)
            data.Code = RegisterService.RegisterServices.TempStudentService.GenerateCode();

          //  data.Name = txtfirstname.Text +" "+ txtlastname.Text;
            data.Active = true;
           // data.BranchID = comboboxUC_Banch.ID;
            data.BranchID = buttonEdit_Branch.EditValue.ToString();
            data.FirstName = txtfirstname.Text;
            data.LastName = txtlastname.Text;
            data.Name = txtfirstname.Text + " " + txtlastname.Text;
            data.Address = txtaddress.Text;
            data.DayOfBirth = dateEdit_dayofbirth.Text;
            data.ContactDate = dateEdit_tempcontact.DateTime;
            data.Content = memoEdit_content.Text;
            if (cbProvince.SelectedItem == null)
                data.Province = "";
            else
               data.Province = cbProvince.SelectedItem.ToString();
            data.ChannelInfoID = (long)buttonEdit_Channel.Tag;
            data.Email = txtemail.Text;
            data.PlaceOfBirth = memoEdit_noisinh.Text;
            if (IsRegister)
            {
                data.IsRegister = IsRegister;
            }
           
            data.Note = txtnote.Text;
            data.Phone = txtphonenum.Text;
            data.ReceptioncontactDate = dateEdit_receptioncontact.DateTime;
            data.ResponseContent = memoEdit_responsecontent.Text;
            data.Sex = (bool)radioGroup_sex.EditValue;

            data.Status = (long)buttonEdit_Status.Tag;
            if (IsRegister == true)
            {
                data.Status = 5; //la dang ky hoc
            }
            
            //  data.Active = ckactive.Checked;
           ID = RegisterService.RegisterServices.TempStudentService.Save(data, ref ErrorMess);
           if (ID > 0)
           {
               UpdateStudentInfo(data);
           }
           return ID;
        }


        public override bool Delete(long SelectedID)
        {
            if (!ckregister.Checked)
            {
                return RegisterService.RegisterServices.TempStudentService.UpdateIsDelete(RegisterService.RegisterServices.TempStudentService.GetByID(SelectedID));
            }
            else
            {
                ErrorMess = "Học viên này đã đăng ký nhập học không được xóa";
                return false;
            }

        }


        private void TempStudentUC_Load(object sender, EventArgs e)
        {
            AddTextChanged(xtraScrollableControl1.Controls);
        }

        private void cmddangkyhoc_Click(object sender, EventArgs e)
        {
            try
            {
                if (ID < 0)
                {
                    MessageControl.ShowMessage("Vui lòng lưu lại thông tin trước khi đăng ký học", "Error", MessageControl.Icon.Error);
                    return;
                }
                Student st = new Student();
                frmSelectClass selectclass = new frmSelectClass();
                if (selectclass.ShowDialog() == DialogResult.OK)
                {
                    st.ClassID = selectclass.ID;
                }
                if (st.ClassID == 0)
                {
                    MessageControl.ShowMessage("Chưa chọn lớp", "Error", MessageControl.Icon.Error);
                    return;
                }

                st.Active = false;
                st.Address = txtaddress.Text;
                st.Bonus = 0;
                if (cbProvince.SelectedItem == null)
                    st.Province = "";
                else
                  st.Province = cbProvince.SelectedItem.ToString();
                st.Code = RegisterService.RegisterServices.StudentService.GenerateCode(st.ClassID);
                st.Name = txtfirstname.Text +" "+txtlastname.Text ;
                st.LastName = txtlastname.Text;
                st.FirstName = txtfirstname.Text;
                st.Note = txtnote.Text;
                st.Email = txtemail.Text;
                st.Phone = txtphonenum.Text;
                st.ChannelInfoID = (long)buttonEdit_Channel.Tag;
                st.TotalFee = ((Class)RegisterService.RegisterServices.ClassService.GetByID(st.ClassID)).Price;
                st.DateOfAdmission = ((Class)RegisterService.RegisterServices.ClassService.GetByID(st.ClassID)).StartDate;
                st.RegisterDate = DateTime.Now;
                st.Sex = (bool)radioGroup_sex.EditValue;
                st.PlaceOfBirth = memoEdit_noisinh.Text;
                st.DateOfBirth = dateEdit_dayofbirth.Text;
                st.TypeOfFee = 1;
                st.Status = 3;//set defult is "Signed up";
                string mess = "";
                var id = RegisterService.RegisterServices.StudentService.Save(st, ref mess);
                if (id > 0)
                {
                    ckregister.Checked = true;
                    IsRegister = true;
                    var st_id = SaveTemp();
                    IsRegister = false;
                    //kiem tra xem trong bang kết quả đã có chưa nếu có rồi thì không thêm
                    var checkExist = RegisterService.RegisterServices.StudentResultService.GetByStudentID(id);
                    if (checkExist == null)
                    {
                        var subjectpointcolumn = RegisterService.RegisterServices.SubjectPointColumnService.GetSubjectPointColumnByClassID(st.ClassID);
                        if (subjectpointcolumn != null)
                        {
                            for (int i = 0; i < subjectpointcolumn.Count; i++)
                            {
                                Student_Result st_r = new Student_Result();
                                st_r.StudentID = id;
                                st_r.Subject_PointColumnID = subjectpointcolumn[i].ID;
                                st_r.Value = 0;
                                RegisterService.RegisterServices.StudentResultService.Save(st_r);
                            }
                        }

                    }

                    //save lich su

                    //luu lai lich su mới
                    Student_History historynew = new Student_History();
                    historynew.StudentID = id;
                    historynew.Content = "Đã đăng ký học lớp " + ((Class)RegisterService.RegisterServices.ClassService.GetByID(st.ClassID)).Name;
                    historynew.Content += " vào ngày " + DateTime.Now.ToShortDateString();
                    RegisterService.RegisterServices.StudentHistoryService.Save(historynew);
                    MessageControl.ShowMessage("Đã đăng ký học thành công, vui lòng trở lại màn hình học viên để cập nhật đầy đủ thông tin", "Info", MessageControl.Icon.Info);
                    Reload();
                }
                else
                {
                    MessageControl.ShowMessage("Có lỗi xảy ra, đăng ký học không thành công", "Error", MessageControl.Icon.Error);
                }
            }
            catch(Exception ex)
            {
                MessageControl.ShowMessage("Có lỗi xảy ra, đăng ký học không thành công \n Chi tiết lỗi: "+ex.Message, "Error", MessageControl.Icon.Error);
            }
        }

        private void buttonEdit_Branch_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var branchs = buttonEdit_Branch.EditValue;
            if (branchs == null)
                branchs = "";
            frmMultiSelectBranch br = new frmMultiSelectBranch(branchs.ToString());
            if (br.ShowDialog() == DialogResult.OK)
            {
                buttonEdit_Branch.EditValue = br.SelectName();
            }
            else
            { 
                buttonEdit_Branch.EditValue = string.Empty;
            }
        }

        private void cmdDatCoc_Click(object sender, EventArgs e)
        {
            frmStudentdeposit frm = new frmStudentdeposit(ID);
            frm.ShowDialog();
        }

        private void buttonEdit_Status_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
           
            frmSelectStudentStatus br = new frmSelectStudentStatus(2);
            if (br.ShowDialog() == DialogResult.OK)
            {

                buttonEdit_Status.Tag = br.ID;
                buttonEdit_Status.Text = br.Name;
            }
            else
            {

                buttonEdit_Status.Tag = 0;
                buttonEdit_Status.Text = string.Empty;
            }
        }

   

        private void buttonEdit_Channel_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmSelectChannel br = new frmSelectChannel();
            if (br.ShowDialog() == DialogResult.OK)
            {
               
                buttonEdit_Channel.Tag = br.ID;
                buttonEdit_Channel.Text = br.Name;
            }
            else
            {
                
                buttonEdit_Channel.Tag = 0;
                buttonEdit_Channel.Text = string.Empty;
            }
        }


        private void UpdateStudentInfo(TempStudent tempStudent)
        {
            Student student = RegisterService.RegisterServices.StudentService.GetByTempStudentID(tempStudent.ID);
            if (student != null)
            {
                if (student.Address != tempStudent.Address)
                {
                    student.Address = tempStudent.Address;
                }
                if (student.Phone != tempStudent.Phone)
                {
                    student.Phone = tempStudent.Phone;
                }
                if (student.Email != tempStudent.Email)
                {
                    student.Email = tempStudent.Email;
                }
                if (student.DateOfBirth != tempStudent.DayOfBirth)
                {
                    student.DateOfBirth = tempStudent.DayOfBirth;
                }
                if (student.Province != tempStudent.Province)
                {
                    student.Province = tempStudent.Province;
                }
                if (student.PlaceOfBirth != tempStudent.PlaceOfBirth)
                {
                    student.PlaceOfBirth = tempStudent.PlaceOfBirth;
                }

                RegisterService.RegisterServices.StudentService.Save(student, ref ErrorMess);
            }
        }      
    }
}
